package com.chzc.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chzc.po.RoleMenu;
import com.chzc.sys.mapper.RoleMapper;
import com.chzc.sys.mapper.RoleMenuMapper;
import com.chzc.sys.service.IRoleMenuService;
import com.chzc.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色权限表 服务实现类
 * </p>
 *
 * @author CV大魔王
 * @since 2021-05-26
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Caching(evict = {
            @CacheEvict(value = "role",allEntries = true),
            @CacheEvict(value = "user",allEntries = true),
            @CacheEvict(value = "menu",allEntries = true)
    })
    public Result saveRoleMenu(String roleId, List<String> menuIds) {
        // 1. 先删除角色菜单关系表数据
        roleMapper.deleteRoleMenuByRoleId(roleId);
        // 2. 再保存新的角色菜单关系表数据
        if (CollectionUtils.isNotEmpty(menuIds)) {
            for (int i = 0; i < menuIds.size(); i++) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setMenuId(menuIds.get(i));
                roleMenu.setRoleId(roleId);
                baseMapper.insert(roleMenu);
            }
        }
        return Result.addSuccess();
    }

}
